package flash.utils;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import flash.events.EventDispatcher;
import flash.events.TimerEvent;

public final class Timer extends EventDispatcher {

	private double _delay;
	private int _repeatCount;
	private int _currentCount;

	private javax.swing.Timer _timer;

	public Timer(final double delay) {
		this(delay, 0);
	}

	public Timer(final double delay, final int repeatCount) {
		_delay = delay;
		_repeatCount = repeatCount;
		_currentCount = 0;

		ActionListener taskPerformer = new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				_currentCount++;
				
				if(_repeatCount == 0 || _currentCount < _repeatCount) {
					dispatchEvent(new TimerEvent(TimerEvent.TIMER));
				} else if(_currentCount == _repeatCount) {
					stop();
					dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
				}
			}
		};

		_timer = new javax.swing.Timer((int) delay, taskPerformer);
	}

	public double delay() {
		return _delay;
	}

	public int repeatCount() {
		return _repeatCount;
	}

	public void repeatCount(final int value) {
		_repeatCount = value;
		if (_repeatCount >= currentCount()) {
			stop();
		}
	}

	public int currentCount() {
		return _currentCount;
	}

	public boolean running() {
		return _timer.isRunning();
	}

	public void reset() {
		_currentCount = 0;
		_timer.restart();
	}

	public void start() {
		if (!running()) {
			_timer.start();
		}
	}

	public void stop() {
		if (running()) {
			_timer.stop();
		}
	}
}
